package com.twu.biblioteca.data;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zgq
 * Date: 13-6-23
 * Time: 下午2:55
 * To change this template use File | Settings | File Templates.
 */
public class BookShelf {
    private String bibliotecaBookDataBaseName;

    public BookShelf(String dataBaseName) {
        this.bibliotecaBookDataBaseName = dataBaseName;
    }

    public List<String> bookList() {
        List<String> bookList = new ArrayList<String>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(bibliotecaBookDataBaseName)));
            String line;
            while((line=reader.readLine())!=null) {
                bookList.add(line);
            }
            reader.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            return bookList;
        }
    }

    public void putBookIntoStore(Book book) {
        try {
            FileWriter writer = new FileWriter(bibliotecaBookDataBaseName, true);
            writer.write(book.toString());
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean canBeReserved(String bookName) {
        Iterator<String> iterator = bookList().iterator();
        String line;
        String bookNameInDataBase;
        while(iterator.hasNext()) {
            line = iterator.next();
            bookNameInDataBase = getBookNameFromLine(line);
            if(bookNameInDataBase.equals(bookName)) return true;
            else if(bookNameInDataBase.contains(bookName)) {System.out.println("Do you mean "+bookNameInDataBase+" ?");}
        }
        return false;
    }

    public void clean() {
        try {
            FileWriter writer = new FileWriter(bibliotecaBookDataBaseName);
            writer.write("");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getBookNameFromLine(String line) {
        return line.substring("Name:".length(), line.indexOf("\t"));
    }
}
